package com.pw.study.flink.exercise;

import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author: linux_future
 * @since: 2022/3/16
 **/
public class School {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        DataStreamSource<String> stream = env.readTextFile("data/file/sc.txt");
        stream.map(x -> {
                     //System.out.println(x);
                    String[] line = x.split(",");
// 2,7,8,4
                    return Tuple2.of(line.length, x);
                }).returns(Types.TUPLE(Types.INT, Types.STRING)).filter(t-> t.f0==4).keyBy(t -> t.f0)
                .process(new KeyedProcessFunction<Integer, Tuple2<Integer, String>, String>() {

                    private MapState<Integer, Object> mapState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        mapState = getRuntimeContext().getMapState(new MapStateDescriptor<Integer, Object>("mapState", Integer.class, Object.class));
                    }

                    @Override
                    public void processElement(Tuple2<Integer, String> value, Context ctx, Collector<String> out) throws Exception {
                        System.out.println(value);
                        if (mapState.contains(value.f0)) {
                            // System.out.println("已存在。。。。");
                        } else {
                            mapState.put(value.f0, new Object());
                            out.collect(value.toString());
                        }
                    }
                }).print();
        //输入数据


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
